package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

// 使用Message来装填jackson解析的前端发来的json格式的字符串。
class Message {
    public String from;
    public String to;
    public String message;
}

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    // 使用jackson解析浏览器发来的json格式的数据
    private ObjectMapper objectMapper = new ObjectMapper();

    // 客户端(浏览器)按提交按钮时，向服务器提交数据
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 将req里的键值对读出，并和Message比对属性名给value，返回Message对象
        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
        // 把这一份表白信息保存到数据库
        int count =  save(message);
        if(count == 1){
            System.out.println("表白信息成功写入数据库");
        }else {
            System.out.println("表白信息写入数据库失败");
        }
    }

    // 浏览器加载时，从服务器获取数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 把messageList这个Java集合对象转成json格式的字符串，再把字符串写入resp的body中

        //注意：一定要记得设置响应报文的格式，否则前端代码会认为是其它格式，可能会按照其它格式解析
        resp.setContentType("application/json; charset=utf-8");
        // 从数据库获取所有表白信息
        List<Message> messageList = load();
        objectMapper.writeValue(resp.getOutputStream(), messageList);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf-8");
        // 从数据库获取所有表白信息
        // 1.获取最后一份表白信息，并从数据库删除
        List<Message> messageList = load();
        if(messageList.size() == 0){
            return;
        }
        Message messageEnd = messageList.get(messageList.size()-1);
        int count = delete(messageEnd);
        if(count == 1){
            System.out.println("表白信息删除成功");
        }else {
            System.out.println("表白信息删除失败");
        }
        // 2.获取删除最后一条信息后的 全部表白信息，并写回到浏览器
        messageList = load();
        objectMapper.writeValue(resp.getOutputStream(), messageList);
    }


    private int save(Message message){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        int count = 0;

        try {
            // 1.获取连接
            connection = DBUtil.getConnection();
            // 2.编写sql
            String sql = "insert into message values(?,?,?)";
            // 3.获取预编译对象，进行预编译
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,message.from);
            preparedStatement.setString(2,message.to);
            preparedStatement.setString(3,message.message);
            // 4.执行sql语句
            count = preparedStatement.executeUpdate();
            // 5.处理结果
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtil.close(connection, preparedStatement, null);
        }
        return count;
    }
    private List<Message> load(){
        // 从数据库查询表白信息，把每条信息都放进这个集合里
        List<Message> messageList = new ArrayList<>();

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            // 1.获取连接
            connection = DBUtil.getConnection();
            // 2.编写sql
            String sql = "select * from message";
            // 3.获取预编译对象，进行预编译
            preparedStatement = connection.prepareStatement(sql);
            // 4.执行sql语句
            resultSet = preparedStatement.executeQuery();
            // 5.处理结果集
            while (resultSet.next()){
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");

                messageList.add(message);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtil.close(connection, preparedStatement, resultSet);
        }
        return messageList;
    }
    private int delete(Message message){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        int count = 0;
        try {
            // 1.获取连接
            connection = DBUtil.getConnection();
            // 2.编写sql
            String sql = "delete from message where `from` = ? and `to` = ? and message = ?";
            // 3.获取预编译对象，进行预编译
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, message.from);
            preparedStatement.setString(2, message.to);
            preparedStatement.setString(3, message.message);
            // 4.执行sql语句
            count = preparedStatement.executeUpdate();
            // 5.处理结果

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtil.close(connection, preparedStatement, null);
        }
        return count;
    }
}
